package com.peanut.baby.mvp.task;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.peanut.baby.AppConfig;
import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.comm.BaseDialog;
import com.peanut.baby.db.DBManager;
import com.peanut.baby.model.Task;
import com.peanut.baby.model.TaskDBRecord;
import com.peanut.baby.mvp.BaseMvpActivity;
import com.peanut.baby.mvp.bbs.publish.BBSPublishActivity;
import com.peanut.baby.mvp.bind.BindMobileActivity;
import com.peanut.baby.mvp.login.LoginActivity;
import com.peanut.baby.mvp.point.PointRecordActivity;
import com.peanut.baby.test.TestUtils;
import com.peanut.baby.util.ShareUtil;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.widget.TitleLayout;
import com.tencent.mars.xlog.Log;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by anonymouslystudio on 2017/8/9.
 */

public class TaskActivity extends BaseMvpActivity implements TitleLayout.OnTitleClickListener,
        View.OnClickListener, TaskContract.View {
    private static final String TAG = TaskActivity.class.getSimpleName();
    @BindView(R.id.title)
    TitleLayout title;
    @BindView(R.id.recommend_task_container)
    LinearLayout recommendTaskContainer;
    @BindView(R.id.point_record)
    LinearLayout pointRecord;
    @BindView((R.id.copywx))
    View copywx;
    private TaskPresenter presenter;

    public static void start(Context ctx) {
        ctx.startActivity(new Intent(ctx, TaskActivity.class));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task);
        ButterKnife.bind(this);
        initViews();
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.d(TAG, "onRestoreInstanceState");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.d(TAG, "onRestoreInstanceState");
    }

    @Override
    protected void onResume() {
        super.onResume();
        testRecommendTasks();
    }

    private void initViews() {
        title.setTitle("每日任务");
        title.setOnTitleClickedListener(this);
        presenter = new TaskPresenter(this, this);
        pointRecord.setOnClickListener(this);
        copywx.setOnClickListener(this);
    }


    private void testRecommendTasks() {
        recommendTaskContainer.removeAllViews();
        List<Task> tasks = TestUtils.getTestRecommendTasks();
        int len = tasks.size();
        TaskListAdapter adapter = new TaskListAdapter(this, tasks);
        for (int i = 0; i < len; i++) {
            final Task task = tasks.get(i);
            final View view = adapter.getView(i, null, null);
            recommendTaskContainer.addView(view);
            view.findViewById(R.id.task_action).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (InitManager.getInstance().getUser() == null) {
                        LoginActivity.startForResult(TaskActivity.this);
                        return;
                    }
                    switch (task.type) {
                        case Task.TYPE_NEW_MOMENT:
                            if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)) {
                                BindMobileActivity.startForResult(TaskActivity.this);
                                return;
                            }
                            BBSPublishActivity.start(TaskActivity.this);
                            break;
                        case Task.TYPE_NEW_REPLY:
                            if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)) {
                                BindMobileActivity.startForResult(TaskActivity.this);
                                return;
                            }
                            sendBroadcast(new Intent(AppConfig.BroadCastConfig.ACTION_TASK_REPLY));
                            break;
                        case Task.TYPE_SHARE_MOMENT:
                            sendBroadcast(new Intent(AppConfig.BroadCastConfig.ACTION_TASK_BBS));
                            break;
                        case Task.TYPE_SHARE_LIVE:
                            sendBroadcast(new Intent(AppConfig.BroadCastConfig.ACTION_TASK_LIVE));
                            break;
                        case Task.TYPE_SHARE_QA:
                            sendBroadcast(new Intent(AppConfig.BroadCastConfig.ACTION_TASK_QA));
                            break;
                        case Task.TYPE_SHARE_APP:
                            new BaseDialog().showShareDialog(TaskActivity.this, new BaseDialog.OnShareItemSelected() {
                                @Override
                                public void onShareItemSelected(int item) {
                                    String platName = "";
                                    if (item == BaseDialog.OnShareItemSelected.TYPE_MOMENT) {
                                        platName = WechatMoments.NAME;
                                    } else if (item == BaseDialog.OnShareItemSelected.TYPE_WEIXIN) {
                                        platName = Wechat.NAME;
                                    } else if (item == BaseDialog.OnShareItemSelected.TYPE_WEIBO) {
                                        platName = SinaWeibo.NAME;
                                    } else if (item == BaseDialog.OnShareItemSelected.TYPE_QQ) {
                                        platName = QQ.NAME;
                                    }
                                    if (StringUtil.isNullOrEmpty(platName)) {
                                        return;
                                    }
                                    ShareUtil.getInstance().shareApp(platName, new ShareUtil.IShareCallback() {
                                        @Override
                                        public void onShareFinished(boolean isSuccess, String platformName, String failReason) {
                                            showToast(isSuccess ? "分享成功" : failReason);
                                            if (isSuccess && InitManager.getInstance().getUser() != null) {
                                                TaskDBRecord record = DBManager.getInstance().getTaskRecord(Integer.parseInt(InitManager.getInstance().getUserId()), com.peanut.devlibrary.util.TimeUtil.getCurrentDate());
                                                record.shareAppCount++;
                                                if (record.shareAppCount > 1) {
                                                    record.shareAppCount = 1;
                                                } else {
                                                    try {
                                                        presenter.sharePoint();
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                                DBManager.getInstance().updateTaskRecord(record);
                                                onShareAppSuccess(view);
                                            }
                                        }
                                    });
                                }
                            });
                            break;

                    }
                }
            });
        }
    }

    private void onShareAppSuccess(final View parentView) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TextView action = (TextView) parentView.findViewById(R.id.task_action);
                action.setText("已完成");
                action.setEnabled(false);
            }
        });

    }

    @Override
    public void onTitleBackClicked() {
        finish();
    }

    @Override
    public void onTitleRightClicked() {

    }

    @Override
    public void onTitleClicked() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.point_record:
                PointRecordActivity.start(this);
                break;
            case R.id.copywx:
                ClipboardManager clipboard = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）
                ClipData clipData = ClipData.newPlainText(null, "huashengkf");
                // 把数据集设置（复制）到剪贴板
                clipboard.setPrimaryClip(clipData);
                showToast("复制成功");
                break;
        }
    }

    @Override
    public void onSharePoint(String tips) {
        showToast(tips);
    }
}
